"""
System Management API Extensions
系统管理API扩展 - 额外的系统管理功能
"""

import uuid
from typing import Optional, Dict, Any, List
from datetime import datetime, timedelta

from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_, or_, func, text

from ..core.database import get_db
from ..core.logging import error_logger
from ..core.exceptions import ValidationError, PermissionDeniedError
from ..core.config import settings
from ..models.user import User
from ..models.system_log import SystemLog, LogLevel, LogCategory
from ..models.generated_content import GeneratedContent, ContentStatus
from ..models.task_queue import TaskQueue, TaskStatus
from ..services.system_monitoring_service import SystemMonitoringService
from ..services.health_check_service import health_check_service
from .auth import get_current_user
from .admin import require_admin

router = APIRouter()


@router.get("/system/info")
async def get_system_info(
    current_user: User = Depends(require_admin),
    db: AsyncSession = Depends(get_db),
):
    """获取系统信息"""
    try:
        system_info = {
            "app_name": settings.app_name,
            "app_version": settings.app_version,
            "app_env": settings.app_env,
            "python_version": "3.11+",  # 可以根据实际版本调整
            "database_url": settings.database.url.split("@")[-1] if "@" in settings.database.url else settings.database.url,
            "max_workers": settings.task_queue.max_workers,
            "max_tasks": settings.task_queue.max_tasks,
            "default_ai_provider": settings.ai_provider.default_provider,
            "features": {
                "content_moderation": settings.content_generation.enable_content_moderation,
                "nsfw_filter": settings.content_generation.nsfw_filter_sensitivity,
                "auto_cleanup": True,
                "multi_language": True,
            },
            "limits": {
                "max_upload_size_mb": settings.file_storage.max_upload_size_mb,
                "guest_daily_generation": settings.user_limit.guest_daily_generation_limit,
                "registered_daily_generation": settings.user_limit.registered_daily_generation_limit,
                "max_concurrent_tasks_per_user": settings.user_limit.max_concurrent_tasks_per_user,
            }
        }
        
        return {
            "success": True,
            "data": system_info
        }
        
    except Exception as e:
        error_logger.log_error(e, {"operation": "get_system_info", "user_id": str(current_user.id)})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取系统信息失败"
        )


@router.get("/system/stats")
async def get_system_statistics(
    current_user: User = Depends(require_admin),
    db: AsyncSession = Depends(get_db),
):
    """获取系统统计信息"""
    try:
        # 用户统计
        user_stats = await db.execute(
            select(
                func.count(User.id).label('total_users'),
                func.count(User.id).filter(User.status == 'active').label('active_users'),
                func.count(User.id).filter(User.role == 'admin').label('admin_users'),
                func.count(User.id).filter(User.status == 'locked').label('locked_users'),
            )
        )
        user_data = user_stats.one()
        
        # 内容统计
        content_stats = await db.execute(
            select(
                func.count(GeneratedContent.id).label('total_content'),
                func.count(GeneratedContent.id).filter(GeneratedContent.status == 'completed').label('completed_content'),
                func.count(GeneratedContent.id).filter(GeneratedContent.status == 'failed').label('failed_content'),
                func.count(GeneratedContent.id).filter(GeneratedContent.status == 'processing').label('processing_content'),
                func.count(GeneratedContent.id).filter(GeneratedContent.status == 'pending').label('pending_content'),
                func.sum(GeneratedContent.file_size_bytes).label('total_storage_bytes'),
            )
        )
        content_data = content_stats.one()
        
        # 任务队列统计
        queue_stats = await db.execute(
            select(
                func.count(TaskQueue.id).filter(TaskQueue.status == TaskStatus.PENDING).label('pending_tasks'),
                func.count(TaskQueue.id).filter(TaskQueue.status == TaskStatus.PROCESSING).label('processing_tasks'),
                func.count(TaskQueue.id).filter(TaskQueue.status == TaskStatus.COMPLETED).label('completed_tasks'),
                func.count(TaskQueue.id).filter(TaskQueue.status == TaskStatus.FAILED).label('failed_tasks'),
            )
        )
        queue_data = queue_stats.one()
        
        # 今日统计
        today_start = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0)
        
        today_content = await db.execute(
            select(func.count(GeneratedContent.id))
            .where(GeneratedContent.created_at >= today_start)
        )
        today_content_count = today_content.scalar()
        
        today_users = await db.execute(
            select(func.count(User.id))
            .where(User.created_at >= today_start)
        )
        today_user_count = today_users.scalar()
        
        statistics = {
            "users": {
                "total": user_data.total_users,
                "active": user_data.active_users,
                "admin": user_data.admin_users,
                "locked": user_data.locked_users,
                "new_today": today_user_count,
            },
            "content": {
                "total": content_data.total_content or 0,
                "completed": content_data.completed_content or 0,
                "failed": content_data.failed_content or 0,
                "processing": content_data.processing_content or 0,
                "pending": content_data.pending_content or 0,
                "total_storage_mb": round((content_data.total_storage_bytes or 0) / (1024 * 1024), 2),
                "new_today": today_content_count,
            },
            "tasks": {
                "pending": queue_data.pending_tasks or 0,
                "processing": queue_data.processing_tasks or 0,
                "completed": queue_data.completed_tasks or 0,
                "failed": queue_data.failed_tasks or 0,
            },
            "system": {
                "timestamp": datetime.utcnow().isoformat(),
                "uptime_seconds": "system_uptime_placeholder",  # TODO: 实现系统运行时间
            }
        }
        
        return {
            "success": True,
            "data": statistics
        }
        
    except Exception as e:
        error_logger.log_error(e, {"operation": "get_system_statistics", "user_id": str(current_user.id)})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取系统统计失败"
        )


@router.get("/system/performance")
async def get_performance_metrics(
    current_user: User = Depends(require_admin),
    hours: int = Query(24, ge=1, le=168, description="统计时间范围（小时）"),
    db: AsyncSession = Depends(get_db),
):
    """获取系统性能指标"""
    try:
        from_time = datetime.utcnow() - timedelta(hours=hours)
        
        # 内容生成性能
        performance_stats = await db.execute(
            select(
                func.avg(GeneratedContent.processing_time_seconds).label('avg_processing_time'),
                func.min(GeneratedContent.processing_time_seconds).label('min_processing_time'),
                func.max(GeneratedContent.processing_time_seconds).label('max_processing_time'),
                func.count(GeneratedContent.id).label('total_processed'),
            )
            .where(
                and_(
                    GeneratedContent.created_at >= from_time,
                    GeneratedContent.status == 'completed',
                    GeneratedContent.processing_time_seconds.isnot(None)
                )
            )
        )
        perf_data = performance_stats.one()
        
        # 按内容类型分组统计
        by_type_stats = await db.execute(
            select(
                GeneratedContent.content_type,
                func.avg(GeneratedContent.processing_time_seconds).label('avg_time'),
                func.count(GeneratedContent.id).label('count'),
            )
            .where(
                and_(
                    GeneratedContent.created_at >= from_time,
                    GeneratedContent.status == 'completed',
                    GeneratedContent.processing_time_seconds.isnot(None)
                )
            )
            .group_by(GeneratedContent.content_type)
        )
        by_type_data = by_type_stats.all()
        
        # 按AI提供商分组统计
        by_provider_stats = await db.execute(
            select(
                GeneratedContent.ai_provider,
                func.avg(GeneratedContent.processing_time_seconds).label('avg_time'),
                func.count(GeneratedContent.id).label('count'),
            )
            .where(
                and_(
                    GeneratedContent.created_at >= from_time,
                    GeneratedContent.status == 'completed',
                    GeneratedContent.processing_time_seconds.isnot(None)
                )
            )
            .group_by(GeneratedContent.ai_provider)
        )
        by_provider_data = by_provider_stats.all()
        
        performance = {
            "time_range_hours": hours,
            "overall": {
                "avg_processing_time_seconds": float(perf_data.avg_processing_time or 0),
                "min_processing_time_seconds": float(perf_data.min_processing_time or 0),
                "max_processing_time_seconds": float(perf_data.max_processing_time or 0),
                "total_processed": int(perf_data.total_processed or 0),
            },
            "by_content_type": [
                {
                    "content_type": content_type,
                    "avg_processing_time_seconds": float(avg_time or 0),
                    "count": int(count or 0),
                }
                for content_type, avg_time, count in by_type_data
            ],
            "by_ai_provider": [
                {
                    "ai_provider": provider,
                    "avg_processing_time_seconds": float(avg_time or 0),
                    "count": int(count or 0),
                }
                for provider, avg_time, count in by_provider_data
            ],
        }
        
        return {
            "success": True,
            "data": performance
        }
        
    except Exception as e:
        error_logger.log_error(e, {"operation": "get_performance_metrics", "user_id": str(current_user.id)})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取性能指标失败"
        )


@router.post("/system/cleanup")
async def run_system_cleanup(
    cleanup_types: List[str] = Query(..., description="清理类型列表"),
    current_user: User = Depends(require_admin),
):
    """运行系统清理任务"""
    try:
        from .cleanup_service import async_cleanup_service
        
        logger.info(f"Running system cleanup: {cleanup_types}")
        
        # 运行清理任务
        cleanup_results = await async_cleanup_service.run_manual_cleanup(cleanup_types)
        
        logger.info(
            "System cleanup completed",
            cleanup_types=cleanup_types,
            duration_seconds=cleanup_results.get("duration_seconds", 0)
        )
        
        return {
            "success": True,
            "data": cleanup_results
        }
        
    except Exception as e:
        error_logger.log_error(e, {"operation": "run_system_cleanup", "user_id": str(current_user.id)})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="系统清理失败"
        )


@router.get("/system/logs/summary")
async def get_logs_summary(
    current_user: User = Depends(require_admin),
    hours: int = Query(24, ge=1, le=168, description="时间范围（小时）"),
    db: AsyncSession = Depends(get_db),
):
    """获取日志摘要"""
    try:
        from_time = datetime.utcnow() - timedelta(hours=hours)
        
        # 按级别统计
        level_stats = await db.execute(
            select(
                SystemLog.level,
                func.count(SystemLog.id).label('count')
            )
            .where(SystemLog.created_at >= from_time)
            .group_by(SystemLog.level)
            .order_by(func.count(SystemLog.id).desc())
        )
        level_data = level_stats.all()
        
        # 按分类统计
        category_stats = await db.execute(
            select(
                SystemLog.category,
                func.count(SystemLog.id).label('count')
            )
            .where(SystemLog.created_at >= from_time)
            .group_by(SystemLog.category)
            .order_by(func.count(SystemLog.id).desc())
        )
        category_data = category_stats.all()
        
        # 最新错误日志
        recent_errors = await db.execute(
            select(SystemLog)
            .where(
                and_(
                    SystemLog.created_at >= from_time,
                    SystemLog.level.in_([LogLevel.ERROR, LogLevel.CRITICAL])
                )
            )
            .order_by(SystemLog.created_at.desc())
            .limit(5)
        )
        error_logs = recent_errors.scalars().all()
        
        summary = {
            "time_range_hours": hours,
            "total_logs": sum(count for _, count in level_data),
            "by_level": [
                {"level": level, "count": count}
                for level, count in level_data
            ],
            "by_category": [
                {"category": category, "count": count}
                for category, count in category_data
            ],
            "recent_errors": [
                {
                    "id": str(log.id),
                    "level": log.level,
                    "category": log.category,
                    "message": log.message,
                    "created_at": log.created_at.isoformat(),
                }
                for log in error_logs
            ],
        }
        
        return {
            "success": True,
            "data": summary
        }
        
    except Exception as e:
        error_logger.log_error(e, {"operation": "get_logs_summary", "user_id": str(current_user.id)})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取日志摘要失败"
        )


@router.post("/system/restart-services")
async def restart_system_services(
    service_names: List[str] = Query(..., description="要重启的服务名称列表"),
    current_user: User = Depends(require_admin),
):
    """重启系统服务（模拟）"""
    try:
        logger.warning(f"Restarting system services: {service_names}")
        
        # 这里可以实现实际的服务重启逻辑
        # 由于安全考虑，这里只是模拟重启过程
        
        restart_results = {}
        
        for service_name in service_names:
            if service_name in ["task_queue", "database", "ai_providers"]:
                # 模拟重启过程
                restart_results[service_name] = {
                    "status": "restarted",
                    "message": f"Service {service_name} restarted successfully",
                    "restart_time": "2024-01-01T00:00:00Z",  # 模拟时间
                }
            else:
                restart_results[service_name] = {
                    "status": "failed",
                    "error": f"Unknown service: {service_name}",
                }
        
        return {
            "success": True,
            "data": {
                "restart_results": restart_results,
                "message": "服务重启请求已处理（模拟）",
            }
        }
        
    except Exception as e:
        error_logger.log_error(e, {"operation": "restart_system_services", "user_id": str(current_user.id)})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="服务重启失败"
        )


@router.get("/system/config")
async def get_system_config(
    current_user: User = Depends(require_admin),
):
    """获取系统配置信息"""
    try:
        # 返回系统配置（敏感信息已过滤）
        config_info = {
            "app": {
                "name": settings.app_name,
                "version": settings.app_version,
                "environment": settings.app_env,
                "debug": settings.debug,
            },
            "server": {
                "host": settings.host,
                "port": settings.port,
            },
            "database": {
                "pool_size": settings.database.pool_size,
                "max_overflow": settings.database.max_overflow,
                "pool_timeout": settings.database.pool_timeout,
            },
            "ai_providers": {
                "default_provider": settings.ai_provider.default_provider,
                "providers_configured": {
                    "doubao": bool(settings.ai_provider.ark_api_key),
                    "ali": bool(settings.ai_provider.ali_api_key),
                    "openai": bool(settings.ai_provider.openai_api_key),
                },
            },
            "security": {
                "jwt_algorithm": settings.security.jwt_algorithm,
                "jwt_expiration_hours": settings.security.jwt_expiration_hours,
                "cors_allow_credentials": settings.security.cors_allow_credentials,
            },
            "limits": {
                "max_upload_size_mb": settings.file_storage.max_upload_size_mb,
                "guest_daily_generation": settings.user_limit.guest_daily_generation_limit,
                "registered_daily_generation": settings.user_limit.registered_daily_generation_limit,
                "max_concurrent_tasks_per_user": settings.user_limit.max_concurrent_tasks_per_user,
                "max_concurrent_tasks_system": settings.user_limit.max_concurrent_tasks_system,
            },
            "features": {
                "content_moderation": settings.content_generation.enable_content_moderation,
                "nsfw_filter": settings.content_generation.nsfw_filter_sensitivity,
                "structured_logging": settings.logging.enable_structured_logging,
            },
        }
        
        return {
            "success": True,
            "data": config_info
        }
        
    except Exception as e:
        error_logger.log_error(e, {"operation": "get_system_config", "user_id": str(current_user.id)})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取系统配置失败"
        )


# 导出路由
__all__ = ["router"]